import { getOrderPage, OrderVO, removeOrder } from '@/services/OrderService'
import { rangePresets } from '@/utils/DateRangeUtils'
import { useAccess } from '@@/exports'
import { ProColumns, ProTable } from '@ant-design/pro-components'
import { ColumnsState } from '@ant-design/pro-table/es/Store/Provide'
import { useModel } from '@umijs/max'
import { Button, Popconfirm, Space } from 'antd'
import dayjs from 'dayjs'
import { useLocalStorage } from 'react-use'

export interface OrderProps {
  onSave?: () => void
  onUpdate?: (record: OrderVO) => void
  tableRef?: any
}

const Order = (props: OrderProps) => {
  const { getDictData } = useModel('dict')
  const access = useAccess()
  const [columnsState, setColumnsState] = useLocalStorage<Record<string, ColumnsState>>('orderTableColumnsState')
  /**
   * 列定义
   */
  const columns: ProColumns<OrderVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '客户id',
      dataIndex: 'customerId',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      width: 120,
      fixed: 'left',
    },
    {
      title: '拍摄类型',
      hideInSearch: true,
      width: 150,
      dataIndex: 'photoType',
      render: (_, record) => getDictData('photo_type', record.photoType)?.label,
    },
    {
      title: '商品id',
      dataIndex: 'goodsId',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '商品名称',
      width: 120,
      dataIndex: 'goodsName',
      hideInSearch: true,
    },
    {
      title: '销售id',
      dataIndex: 'sellerId',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '销售',
      width: 120,
      dataIndex: 'sellerName',
      hideInSearch: true,
    },
    {
      title: '商品价格',
      width: 120,
      dataIndex: 'goodsPrice',
      hideInSearch: true,
      render: (_, record) => `¥${record.goodsPrice / 100}`,
    },
    {
      title: '实际价格',
      width: 120,
      dataIndex: 'realPrice',
      hideInSearch: true,
      render: (_, record) => `¥${record.realPrice / 100}`,
    },
    {
      title: '已付金额',
      width: 120,
      dataIndex: 'alreadyPay',
      hideInSearch: true,
      render: (_, record) => `¥${record.alreadyPay / 100}`,
    },
    {
      title: '欠款',
      width: 120,
      dataIndex: 'arrears',
      hideInSearch: true,
      render: (_, record) => `¥${record.arrears / 100}`,
    },
    {
      title: '预计拍摄日期',
      width: 180,
      valueType: 'date',
      render: (_, record) => record.expectPhotoTime && dayjs(record.expectPhotoTime).format('YYYY-MM-DD HH:mm'),
      dataIndex: 'expectPhotoTime',
      hideInSearch: true,
    },
    {
      title: '备注',
      width: 120,
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '创建人id',
      dataIndex: 'creatorId',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      width: 180,
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '日期范围',
      dataIndex: 'startTime',
      valueType: 'dateRange',
      hideInTable: true,
      fieldProps: {
        presets: rangePresets,
      },
      initialValue: [dayjs().startOf('month'), dayjs().endOf('month')],
      search: {
        transform: (value) => {
          return {
            startTime: value[0] + ' 00:00:00',
            endTime: value[1] + ' 23:59:59',
          }
        },
      },
    },
    {
      title: '更新时间',
      width: 180,
      dataIndex: 'updateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      render: (_: any, record: OrderVO) => [
        <Space key="operate">
          {access.hasOrderUpdatePerm && (
            <Button type="link" size="small" onClick={() => props.onUpdate && props.onUpdate(record)}>
              编辑
            </Button>
          )}
          {access.hasOrderRemovePerm && (
            <Popconfirm
              title="确定要删除吗"
              onConfirm={() => {
                removeOrder(record.id).then(() => {
                  props.tableRef?.current?.reload()
                })
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button type="link" danger size="small">
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>,
      ],
      hideInSearch: true,
      hideInTable: !(access.hasOrderUpdatePerm || access.hasOrderRemovePerm),
      fixed: 'right',
    },
  ]

  // 工具栏
  let actions = [
    props?.onSave && (
      <Button key="create" type="primary" onClick={props.onSave}>
        创建订单
      </Button>
    ),
  ]

  return (
    <>
      <ProTable
        columnsStateMap={columnsState}
        onColumnsStateChange={setColumnsState}
        actionRef={props.tableRef}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['20', '50', '100'],
        }}
        scroll={{ x: 500 }}
        sticky={{ offsetHeader: 55, offsetScroll: 5 }}
        columnEmptyText={false}
        defaultSize="small"
        revalidateOnFocus
        columns={columns}
        request={getOrderPage}
        toolbar={{
          actions: actions,
        }}
      />
    </>
  )
}

export default Order
